package com.WebSocket;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;



@Component
// 配置websocket的接口，userId用于区分不同的用户的前端
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    /**
     * 用户ID
     */
    private String userId;
    public static Set<WebSocket> webSockets =new HashSet<>();
    // 用来存在线连接用户信息
    public static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<String,Session>();



    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        // 前端与后端建立连接
        try {
            this.session = session;
            System.out.println(this.session);
            this.userId = userId;
            System.out.println(this.userId);
            webSockets.add(this);

            // 存储该用户的session，后续可通过该session主动向前端发送消息
            sessionPool.put(userId, session);
            // log.info("【websocket消息】有新的连接，总数为:"+webSockets.size());
        } catch (Exception e) {
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        // 用户前端断开websocket(退出登录)
        try {
            webSockets.remove(this);

            // 删除该用户的session
            sessionPool.remove(this.userId);
            // log.info("【websocket消息】连接断开，总数为:"+webSockets.size());
        } catch (Exception e) {
        }
    }

    // 其他类中通常通过此方法发送信息
    public static void sendOneMessage(Integer userId, SocketData data) {
        sendOneMessage(String.valueOf(userId), data);
    }

    public static void sendOneMessage(String userId, SocketData data) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            sendOneMessage(userId, objectMapper.writeValueAsString(data));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    // 向前端发送消息，内容为message，接收用户id为userId
    public static void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                // log.info("【websocket消息】 单点消息:"+message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof WebSocket) {
            return this.userId.equals(((WebSocket) obj).userId);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return this.userId.hashCode();
    }
}
